<template>
  <view>
    <!--pages/scanDevices/scanDevices.wxml-->

    <view class="page-list-header">
      <h2>设备列表</h2>
    </view>
    <view class="page-body">
      <!-- <button bindtap="scanDeviceList">开始扫描</button>
  <button bindtap="stopScanDeviceList">结束扫描</button> -->
      <view class="log">
        <view>日志(可滑动查看)：</view>
        <view>
          <scroll-view scroll-y="true" class="text-box scroll-list">
            <text>{{ textLog }}</text>
          </scroll-view>
        </view>
      </view>
      <view class="scan-view">
        <button class="btn">清空log日志</button>
      </view>
      <view class="devices-summary"
        >发现 {{ devices.length }} 个相关设备：</view
      >
      <scroll-view class="device-list" scroll-y scroll-with-animation>
        <view
          v-for="(item, index) in devices"
          :key="index"
          :data-device-id="item.deviceId"
          :data-mac-addr="item.macAddr"
          :data-name="item.name || item.localName"
          @tap="createBLEConnection"
          class="device-item"
          hover-class="device-item-hover"
        >
          <view style="font-size: 16px; color: #333">{{ item.name }}</view>
          <view style="font-size: 10px"
            >信号强度: {{ item.RSSI }}dBm ({{
              utils.max(0, item.RSSI + 100)
            }}%)</view
          >
          <view style="font-size: 10px">UUID: {{ item.deviceId }}</view>
          <view style="font-size: 10px">MAC地址: {{ item.macAddr }}</view>
          <view style="font-size: 10px"
            >Service数量: {{ utils.len(item.advertisServiceUUIDs) }}</view
          >
          <view class="fr" style="position: absolute; top: 30rpx; right: 20rpx">
            <text>连接设备</text>
            <icon
              class="ico-arrow-right"
              style="position: relative; top: 4rpx"
            ></icon>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script module="utils" lang="wxs" src="./utils.wxs"></script>

<script>
var app = getApp();
var utils = require("../../utils/util.js");
export default {
  data() {
    return {
      blueAdapter: false,
      textLog: "",
      devices: [],
      connected: false,
      currentDeviceType: "",
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      currentDeviceType: options.deviceType,
      perfix: options.perfix,
      blueAdapter: false,
      connected: false,
      devices: [],
      textLog: "",
    });
    this._openBluetoothAdapter();
    // this.getBlueAdapterState()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  onShow: function () {},
  onUnload: function () {
    this._stopBluetoothDevicesDiscovery();
  },
  methods: {
    /**
     * @description: 第一步 初始化蓝牙模块
     * @param {*}
     * @return {*}
     */
    _openBluetoothAdapter() {
      let _this = this
      uni.openBluetoothAdapter({
        success() {
          _this._getBlueAdapterState();
        },
        fail(err) {
          console.log('openBluetoothAdapter', err)
          uni.showModal({
            title: "提示",
            content: "蓝牙开关未开启",
            showCancel: false,
          });
        }
      });
    },
    /**
     * @description: 第二步 获取本机蓝牙适配器状态
     * @param {*}
     * @return {*}
     */
    _getBlueAdapterState() {
      let _this = this
      uni.getBluetoothAdapterState({
        success(data) {
          if (data.available) {
            _this._startBluetoothDevicesDiscovery();
          }
        },
        fail(err) {
          console.log('getBluetoothAdapterState', err)
        }
      });
    },
    _onBluetoothAdapterStateChange() {
      uni.onBluetoothAdapterStateChange((res) => {
        let { code, data, msg } = res;
        if (code == 0) {
          if (data.available) {
            this._startBluetoothDevicesDiscovery();
          }
        }
      });
    },
    /**
     * @description: 第三步 开始搜索蓝牙设备
     * @param {*}
     * @return {*}
     */
    _startBluetoothDevicesDiscovery() {
      let _this = this
      uni.startBluetoothDevicesDiscovery({
        services: [],
        allowDuplicatesKey: false,
        interval: 1000,
        success(res) {
          _this._onBluetoothDeviceFound();
        },
        fail(err) {
          console.log('startBluetoothDevicesDiscovery', err)
        }
      })
    },
    /**
     * @description: 第四步 监听搜索到蓝牙设备
     * @param {*}
     * @return {*}
     */
    _onBluetoothDeviceFound() {
      let _this = this
      uni.onBluetoothDeviceFound((data) => {
        let deviceArr = [..._this.devices];
        console.log('搜索记录1', data.deviceArr)
        console.log('搜索记录2', data.devices)
        if (data.devices.length) {
          data.devices.map((v) => {
            if (v.name || v.localName) {
              let blueName = v.name || v.localName;
              if (true) {
              // if (utils.prefixInName(_this.perfix, blueName)) {
                if (blueName == 'Oximeter-BLE') {
                  console.error(utils
                  .ab2hex(v.advertisData)
                  .toUpperCase())
                }
                let macAddrStr = utils
                  .ab2hex(v.advertisData)
                  .toUpperCase()
                  .replace(/(.{2})/g, "$1:");
                if (blueName == 'HeartRate Scale') {
                  console.log(macAddrStr)
                }
                if (blueName == 'QN-HS') {
                  v.macAddr = macAddrStr.substring(
                    macAddrStr.length - 21,
                    macAddrStr.length - 3
                  )
                  v.macAddr = [...v.macAddr].reverse().join('')
                } else {
                  v.macAddr = macAddrStr.substring(
                    macAddrStr.length - 18,
                    macAddrStr.length - 1
                  );
                }
                let idx = deviceArr.findIndex((d) => {
                  return d.deviceId == v.deviceId;
                });
                // console.log('搜索到的设备', deviceArr)
                if (idx == -1) {
                  deviceArr.push(v);
                }
              }
            }
            return v;
          });
          _this.setData({
            devices: deviceArr,
          });
        }
      });
    },

    _stopBluetoothDevicesDiscovery() {
      uni.stopBluetoothDevicesDiscovery();
      // uni.offBluetoothDeviceFound((res) => {
      //   console.log(22, res)
      // });
    },
    createBLEConnection: function (e) {
      var ds = e.currentTarget.dataset;
      app.globalData.bindDeviceList.unshift({
        productCode: this.currentDeviceType,
        macId: ds.deviceId,
        macAddr: ds.macAddr,
        deviceName: ds.name,
      });
      this._stopBluetoothDevicesDiscovery()
      uni.navigateTo({
        url: "/pages/selectDevice/v2_startpage",
      });
    },
  },
};
</script>
<style>
/* pages/scanDevices/scanDevices.wxss */
.log {
  width: 90%;
  left: 5%;
  position: relative;
  margin-top: 10rpx;
}

.scroll-list {
  max-height: 300rpx;
}

.scan-view {
  width: 100%;
  margin-top: 30rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.scan-view button {
  position: relative;
  display: block;
  margin-left: auto;
  margin-right: auto;
  padding-left: 28rpx;
  padding-right: 28rpx;
  box-sizing: border-box;
  font-size: 36rpx;
  width: 48%;
}

.devices-summary {
  margin-top: 60rpx;
  padding: 20rpx 5%;
  font-size: 32rpx;
}

.device-list {
  height: 400rpx;
  margin: 100rpx 5%;
  margin-top: 0;
  border: 2rpx solid #eee;
  border-radius: 10rpx;
  width: auto;
}

.device-item {
  border-bottom: 2rpx solid #eee;
  padding: 20rpx;
  color: #666;
  position: relative;
}

.device-item-hover {
  background-color: rgba(0, 0, 0, 0.1);
}
</style>
